package com.riguz.forks.framework.db.impl;

import java.util.Properties;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.riguz.forks.framework.db.PoolManager;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

public class HikariPoolManager extends PoolManager {
    private static final Logger logger = LoggerFactory.getLogger(HikariPoolManager.class);

    @Override
    public DataSource createPool(String name, Properties p) {
        releasePool(name);

        HikariConfig config = new HikariConfig(p);
        config.setPoolName(name);
        // DBUtils execute methods require autoCommit to be true.
        config.setAutoCommit(true);

        HikariDataSource ds = new HikariDataSource(config);
        pools.put(name, ds);
        logger.info("Initialized pool '{}' :[{}]", name, config);
        return ds;
    }

    @Override
    public synchronized void releasePool(String name) {
        logger.info("Releasing datasource:{}", name);
        HikariDataSource ds = (HikariDataSource)pools.get(name);
        if(ds != null)
            ds.close();
        else
            logger.warn("Pool not exist");
    }

}
